#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_io.h"
#include "iot_time.h"

#define UART_BUFF_SIZE 100
#define SR04_Task_STACK_SIZE 1024 * 1
#define SR04_Task_PRIO 25
#define Echo  8   //Echo   //GPIO8
#define Trig  7   //Trig   //GPIO7
#define GPIO_FUNC 0

float GetDistance  (void) {
    static unsigned long start_time = 0, time = 0;
    float distance = 0.0;
    IotGpioValue value = IOT_GPIO_VALUE0;
    unsigned int flag = 0;
            /*
=============== GPIO通信模式流程 1初始化GPIO========================================
            */
    IoTIoSetFunc(Echo, GPIO_FUNC);//设置Echo连接IO为普通GPIO模式，无复用
    IoTGpioSetDir(Echo, IOT_GPIO_DIR_IN);//设置Echo连接IO为输入模式
    IoTGpioSetDir(Trig, IOT_GPIO_DIR_OUT);//设置Trig连接IO为输出模式
            /*
=============== GPIO通信模式流程 2输出起始信号========================================
            */
    IoTGpioSetOutputVal(Trig, IOT_GPIO_VALUE1);//拉高Trig
    IoTUdelay(20);//20us
    IoTGpioSetOutputVal(Trig, IOT_GPIO_VALUE0);//拉低Trig
           /*
=============== GPIO通信模式流程 3检测Echo脚输出的高电平时间========================================
            */
    while (1) {
        IoTGpioGetInputVal(Echo, &value);//读取Echo脚的电平状态
        if ( value == IOT_GPIO_VALUE1 && flag == 0) {//如果为高
            start_time = IoTGetUs();//获取此时时间
            flag = 1;
        }
        if (value == IOT_GPIO_VALUE0 && flag == 1) {//高电平结束变成低电平
            time = IoTGetUs() - start_time;//计算高电平维持时间
            start_time = 0;
            break;
        }
    }
               /*
=============== GPIO通信模式流程 4代入公式计算========================================
            */
    distance = time * 0.034 / 2;
    // printf("distance is %f\r\n",distance);
    return distance;
}

static void SR04_Task(void)
{
    float a = 0.0;
    while(1)
    {
        a = GetDistance();
        printf("distance is %f\r\n",a);
        usleep(500*1000);
    }
}

static void start(void) {
     osThreadAttr_t attr;
    attr.name = "SR04_Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = SR04_Task_STACK_SIZE;
    attr.priority = SR04_Task_PRIO;

    if (osThreadNew((osThreadFunc_t)SR04_Task, NULL, &attr) == NULL)
    {
        printf("[ADCExample] Falied to create SR04_Task!\n");
    }
    printf("初始化成功。。。\r\n");
}

APP_FEATURE_INIT(start);
